// [文件名]
const
    http = require("http"),
    fs = require("fs"),
    httpProxy = require('http-proxy'),
    pcRu = '/Volumes/jacky/1C20积分商城2.0/1C14HTML/pc',
    mobileRu = '/Volumes/jacky/1C20积分商城2.0/1C14HTML/mobile/';

let
    proxy = httpProxy.createProxyServer({}),
    serverStar = (rootUrl, port) => {
        http.createServer((request, response) => {
            let
                url = request.url,
                pathUrl = url.substr(url.indexOf('/', 1)),
                fileUrl = rootUrl + pathUrl,
                txt = fileUrl.slice(fileUrl.lastIndexOf('.') + 1);

            // if (txt === 'html') {
            //     let str = fileUrl.split('/');
            //     str[str.length - 1] = "html/" + str[str.length - 1];
            //     fileUrl = str.join('/');
            // }

            openHtml(response, fileUrl, txt);
        }).listen(port);
    },
    openHtml = (res, path, txtType) => {
        fs.readFile(path, (err, data) => {
            if (err) {
                res.writeHead(404, { "Content-Type": "text/html;" });
                res.end('404');
            } else {
                res.writeHead(200, { "Content-Type": "text/" + txtType + ";charset=\"utf-8\"" });
                res.write(data);
                res.end();
            }
        });
    },
    agentFrom = (port) => {
        http.createServer((req, res) => {
            let
                url = req.url,
                host = url.split('/')[1],
                ip = req.headers['x-forwarded-for'] || req.connection.remoteAddress;

            // 在这里可以自定义你的路由分发  
            switch (host) {
                case 'pc':
                    proxy.web(req, res, { target: 'http://localhost:9001' });
                    break;
                case 'mobile':
                    proxy.web(req, res, { target: 'http://localhost:9002' });
                    break;
                default:
                    res.writeHead(200, { "Content-Type": "text/html;" });
                    res.end('welcome');
            }

        }).listen(port);
    };

// 捕获异常  
proxy.on('error', (err, req, res) => {
    res.writeHead(500, { 'Content-Type': 'text/plain' });
    res.end('Something went wrong. And we are reporting a custom error message.');
});
// 监听pc端页面
serverStar(pcRu, 9001);
// 监听移动端页面
serverStar(mobileRu, 9002);
// 开启反向代理
agentFrom(9000);